package com.dq.demos.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.dq.demos.web.pojo.ReqParamVO;
import com.dq.demos.web.pojo.ThirdUserBo;
import com.dq.demos.web.service.IYFKService;
import com.dq.demos.web.service.IZLBToYFKService;
import com.dq.demos.web.utils.InvoiceOfdUtil;
import com.dq.demos.web.utils.ZLBInvoiceOFDUtil;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import com.alibaba.fastjson.JSONObject;
import com.dq.demos.web.pojo.ReqParamVO;
import com.dq.demos.web.pojo.ThirdUserBo;
import com.dq.demos.web.service.IYFKService;
import com.dq.demos.web.utils.HttpClientUtil;
import com.dq.demos.web.utils.ZLBInvoiceOFDUtil;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/ToYFKService")
public class FPToYonFKController {
    private static Logger logger = LoggerFactory.getLogger(FPToYonFKController.class);
    public SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
    public SimpleDateFormat ymds = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private IYFKService yfkService;
    @Autowired
    private ThirdUserBo thirdUserBo;
    @Autowired
    private IZLBToYFKService ZLBToYFKService;

    @RequestMapping({"/downloadFileURLIO"})
    public ResponseEntity<InputStreamResource>  downloadFile(@RequestBody Map map) throws IOException {
        Object attachmentPath = map.get("attachmentPath");
        Object attachmentType = map.get("attachmentType");
        Object att = map.get("attachmentName");
        String attname = att + "." + attachmentType;
        String attachmentName = attname.replaceAll("[<>:\"/\\\\|?*]", "_");
        // 打开到外部文件的连接
        URL url = new URL(attachmentPath.toString());
        InputStream inputStream = url.openStream();

        // 设置响应头信息
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/ofd"));
        headers.setContentDispositionFormData("attachment", attachmentName);

        // 返回响应实体
        return ResponseEntity.ok()
                .headers(headers)
                .body(new InputStreamResource(inputStream));
    }
    /**
     * 发票上传友费控
     * @param reqParamVO  发票信息
     * @return
     * @throws Exception
     */
    @RequestMapping("/fpUpload")
    public String invoiceUploadService(@RequestBody ReqParamVO reqParamVO) throws  Exception{
        logger.info("----begin----> 后台任务开始准备 上传 发票至费控系统");
        String ksDate = reqParamVO.getBeginDate();
        String jsDate = reqParamVO.getEndDate();
        Date startDate = ymd.parse(ksDate);
        Date endDate = ymd.parse(jsDate);
        logger.info("----> 后台任务同步上传费控参数:【" + reqParamVO.toString() +"】 ");
        while(startDate.compareTo(endDate) <= 0){// 一天一天上传
            String start_Date = ymd.format(startDate);
            try{
                logger.info("开始上传【" + start_Date + "】的发票到费控系统");
                ZLBInvoiceOFDUtil ofdUtil = new ZLBInvoiceOFDUtil();
                List<JSONObject> lists = ZLBToYFKService.post_zlbp_ofd(start_Date);
//                List<JSONObject> lists = ofdUtil.post_zlbp_ofd(start_Date); // 当天需要上传的发票信息
                if(lists.size() <= 0){
                    logger.info("---->日期:【"+startDate+"】，不存在需要上传到费控的发票信息!");
                    continue;
                }
                // 1. 获取费控token
                String toKenURL = thirdUserBo.getBaseURL()+thirdUserBo.getSuffixTokenURL();
                String token = yfkService.getToken(toKenURL, thirdUserBo.getAppKey(), thirdUserBo.getAppSecret());
                logger.info("---->发票上传进项票夹; accessToken = " + token) ;
                HashMap<String, String> acctokenmap = new HashMap<>();
                acctokenmap.put("access_token", token);
                for(JSONObject json : lists){
                    try {
                        JSONObject ofdjson = json.getJSONObject("odf"); // 源文件解析
                        // 2 调用源文件解析接口
                        String odfURL =  thirdUserBo.getBaseURL() + thirdUserBo.getSuffixOFDURL();
                        // 3 处理源文件解析接口信息
                        String odfres = yfkService.uploadYfkJXPJ(odfURL, acctokenmap, ofdjson);
                        JSONObject odfresp = JSONObject.parseObject(odfres);
                        if ("200".equals(odfresp.getString("code").toString())) {
                            String imageId = odfresp.getJSONObject("data").getString("imageId");
                            String billType = odfresp.getJSONObject("data").getString("billType");
                            JSONObject data = json.getJSONObject("data");
                            // 4. 处理进项企业票夹 请求参数
                            data.getJSONArray("bills").getJSONObject(0).put("imageId", imageId);
                            data.getJSONArray("bills").getJSONObject(0).put("billType", billType);
                            //5. 调用接口 请求进项企业票夹接口
                            String jxpjURL = thirdUserBo.getBaseURL()+thirdUserBo.getSuffixJXPKURL();
                            String res = yfkService.uploadYfkJXPJ(jxpjURL, acctokenmap, data);
                            JSONObject resp = JSONObject.parseObject(res);
                            // 6. 处理进项企业票夹接口响应
                            if("200".equals(resp.getString("code"))){
                                logger.info("---->发票上传进项票夹响应信息: " + res);
                            }else{
                                throw new Exception("---->当前发票信息:【"+data+"】上传进项票夹异常 ： " + resp);
                            }
                            Thread.sleep(1000);
                        }else {
                            throw new Exception("源文件解析接口异常,接口相应信息： " + odfresp);
                        }
                    }catch (Exception e){
                        logger.error("------>附件上传费控异常:" + e.getMessage());
                    }

                }

                startDate = addDays(startDate, 1);
                logger.info("---->上传【" + start_Date + "】的发票完毕");
            }catch (Exception e){
                startDate = addDays(startDate, 1);
                logger.error("--->上传【"+start_Date+"】发票至费控异常：异常信息: 【"+e.getMessage()+"】");
                continue;
            }


        }
        logger.info("----end----> 后台任务结束 上传 发票至费控系统");
        return "发票传输完成，是否异常请查看跳板系统日志!日志路径【C:\\yonyou\\log】";
    }

    /**
     * 往后增加天数
     * @param date
     * @param days
     * @return
     */
    protected Date addDays(Date date, int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, days); // 增加一天
        return calendar.getTime();
    }
}